import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

export const Layout = () => import("@/layout/index.vue");

// 静态路由
export const constantRoutes: RouteRecordRaw[] = [
  // {
  //   path: "/",
  //   name: 'home',
  //   component: () => import('../components/HelloWorld.vue')
  // },
  {
    path: "/login",
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path: "/",
    name: '/',
    component: Layout,
    children: [
      {
        path: 'goods',
        name: 'goods',
        meta:{
          isShow:true,
          title:'商品列表'
        },
        component: () => import('../views/demo/GoodsView.vue'),
        children: [
          {
            path: 'add',
            name: 'add',
            meta:{
              isShow:true,
              title:'添加商品'
            },
            component: () => import('../views/demo/GoodsView.vue')
          }
        ]
      },
      {
        path: 'user',
        name: 'user',
        meta:{
          isShow:true,
          title:'用户列表'
        },
        component: () => import('../views/demo/UserView.vue')
      }
    ]
  }
];

/**
 * 创建路由
 */
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("accessToken");  // 获取token
  if(to.name != 'login'){  //如果不是去登录页面需要判断是否有token
      if (!token){
          next({name:"login"});
      }else {
          next();
      }

  }else {
      next();
  }

})

/**
 * 重置路由
 */
export function resetRouter() {
  router.replace({ path: "/login" });
}

export default router;
